<template>
  <div>
    <div v-if="currentValue && currentValue.attachmentId > 0" style="margin-bottom: 10px;">
      <ul class="upload-img-list">
        <li>
          <div class="img-box-wrap">
            <i class="i-remove el-icon-circle-close" title="移除" @click="deleteItem(currentValue)"></i>
            <img width="120" height="120" :src="currentValue.url">
          </div>
        </li>
      </ul>
    </div>
    <image-selector-dialog ref="imageSelector" :image-size-class="imageSizeClass" @save="getSelectedItem"></image-selector-dialog>
    <el-button @click="open()">选择图片</el-button>
  </div>
</template>

<script>
import ImageSelectorDialog from "@/components/ImageSelectorDialog";

export default {
  name: "ImageSingleSelector",
  components: {
    "image-selector-dialog": ImageSelectorDialog
  },
  props: {
    attachmentId: {
      type: Number,
      default: 0
    },
    imageSizeClass: {
      type: String,
      default: "-zoom.120.120"
    },
    value: {
      type: Object,
      default: () => {
        return undefined;
      }
    }
  },
  data() {
    return {
      currentValue: this.value
    };
  },
  watch: {
    value(newValue) {
      this.currentValue = newValue;
    }
  },
  methods: {
    updateValue(newValue) {
      this.$emit("input", newValue);
    },
    // 从已选图片列表中删除某张图片
    deleteItem(item) {
      this.currentValue = undefined;
    },
    // 打开选择图片和上传图片的Dialog
    open() {
      this.$refs["imageSelector"].open();
    },
    getSelectedItem(selectedItem) {
      const item = selectedItem;
      item.displayOrder = 0;
      this.currentValue = item;
      this.updateValue(this.currentValue);
    }
  }
};
</script>
